//
//  DDUserAccount.swift
//  SinaMicroBlog
//
//  Created by dqw on 15/7/29.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class DDUserAccount: NSObject,NSCoding {
    
    var access_token:String?
    var expires_in: NSTimeInterval = 0{
        didSet{
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var expiresDate:NSDate?
    var uid: String?
    var name:String?
    var avatar_large:String?
    static private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    // TODO: 此处暂时将private去掉
    static var aUserAccount: DDUserAccount?
    
    class var isUserLogOn:Bool {
        return loadUserAccount() != nil
    }
    
    func getAnotherUserInfoAndSaveUserAccount(result: [String: AnyObject]) {
        
        name = result["name"] as? String
        uid = result["uid"] as? String
        saveUserAccount()
    }
    
   private func saveUserAccount(){
        NSKeyedArchiver.archiveRootObject(self, toFile: DDUserAccount.accountPath)
    }
    class func loadUserAccount()-> DDUserAccount?{
        if aUserAccount == nil{
            aUserAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? DDUserAccount
        }
        if let data = aUserAccount?.expiresDate where data.compare(NSDate()) == NSComparisonResult.OrderedAscending{
            aUserAccount = nil
        }
        return aUserAccount
    }
    
    
    init(dict:[String:AnyObject]){
        super.init()
        setValuesForKeysWithDictionary(dict)
        // TODO: 测试，这个静态对象的赋值先取消。
        DDUserAccount.aUserAccount = self
    }
    
    func encodeWithCoder(aCoder: NSCoder){
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    required init?(coder aDecoder: NSCoder){
        aDecoder.decodeObjectForKey("access_token") as? String
        aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        aDecoder.decodeDoubleForKey("expires_in")
        aDecoder.decodeObjectForKey("uid") as? String
        aDecoder.decodeObjectForKey("name") as? String
        aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
    override var description:String{
        
        let properties = ["access_token", "expires_in", "uid"]
        return "\(dictionaryWithValuesForKeys(properties))"
    }
}
